package com.mall.common.util;



import com.mall.common.exception.UnauthenticatedException;
import com.mall.common.model.UserAuth;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 安全工具类 - 提供与安全上下文相关的工具方法
 */
public class SecurityUtils {

    private SecurityUtils() {
        // 私有构造器防止实例化
    }

    /**
     * 获取当前认证信息
     * @return 认证对象
     * @throws UnauthenticatedException 如果用户未认证
     */
    public static Authentication getAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        checkAuthentication(authentication);
        return authentication;
    }

    /**
     * 获取当前用户认证信息
     * @return 用户认证对象
     * @throws UnauthenticatedException 如果用户未认证
     */
    public static UserAuth getCurrentUserAuth() {
        Authentication authentication = getAuthentication();
        Object principal = authentication.getPrincipal();

        if (!(principal instanceof UserAuth)) {
            throw new UnauthenticatedException("无效的用户认证信息");
        }

        return (UserAuth) principal;
    }

    /**
     * 获取当前用户ID
     * @return 用户ID
     * @throws UnauthenticatedException 如果用户未认证
     */
    public static Long getCurrentUserId() {
        return getCurrentUserAuth().getUserId();
    }

    /**
     * 获取当前用户名
     * @return 用户名
     * @throws UnauthenticatedException 如果用户未认证
     */
    public static String getCurrentUsername() {
        return getCurrentUserAuth().getUsername();
    }

    /**
     * 检查用户是否已认证
     * @return 是否已认证
     */
    public static boolean isAuthenticated() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null
            && authentication.isAuthenticated()
            && !"anonymousUser".equals(authentication.getPrincipal());
    }

    /**
     * 设置安全上下文
     * @param authentication 认证信息
     */
    public static void setAuthentication(Authentication authentication) {
        SecurityContext context = SecurityContextHolder.createEmptyContext();
        context.setAuthentication(authentication);
        SecurityContextHolder.setContext(context);
    }

    /**
     * 清除安全上下文
     */
    public static void clearContext() {
        SecurityContextHolder.clearContext();
    }

    // 内部方法：检查认证状态
    private static void checkAuthentication(Authentication authentication) {
        if (authentication == null
            || !authentication.isAuthenticated()
            || "anonymousUser".equals(authentication.getPrincipal())) {
            throw new UnauthenticatedException("用户未登录");
        }
    }
}
